package com.redmoon.oa.flow.macroctl;

import cn.js.fan.util.ErrMsgException;
import cn.js.fan.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.entity.Department;
import com.cloudweb.oa.service.IDepartmentService;
import com.cloudweb.oa.utils.ConstUtil;
import com.cloudweb.oa.utils.SpringUtil;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.kit.util.FileUpload;
import com.redmoon.oa.dept.DeptDb;
import com.redmoon.oa.dept.DeptUserDb;
import com.redmoon.oa.flow.FormDb;
import com.redmoon.oa.flow.FormField;
import com.redmoon.oa.person.UserDb;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: qcg
 * @Description:
 * @Date: 2017/12/6 14:59
 */
public class DeptMultiSelectCtl extends AbstractMacroCtl {
    public DeptMultiSelectCtl() {
    }

    /**
     * 此方法用于 添加or编辑页面时 拼成html返回到td中，此处只需拼成一个input和选择按钮
     *
     * @param request HttpServletRequest
     * @param ff      FormField
     * @return 返回值样式:<input id="" name="" value="" size=20 readonly><input id="" name="" value="" type="hidden"><input 选择>
     */
    @Override
    public String convertToHTMLCtl(HttpServletRequest request, FormField ff) {
        /*//页面真正显示的input
        String html = "<input id='" + ff.getName()+"_realshow' name='" +ff.getName()+"_realshow' value='' size=20 readonly />";
        //隐藏input，用于存放实际deptcode
        html += "<input id='"+ff.getName()+"' name='" +ff.getName()+"' value='' type='hidden' />";
        //String html = "<input id='cssss' name='cssss' value='' type='hidden' />";
        //生成选择按钮
        html += "<input id='"+ff.getName()+ "_btn' type='button' class='btn' value='选择' onclick='openWinDeptsSelect(o(\"" + ff.getName()+"\"))' />";
        return html;*/

        String limitDepts = "";
        String desc = ff.getDescription();
        if (StringUtils.isNotEmpty(desc)) {
            org.json.JSONObject json;
            try {
                json = new org.json.JSONObject(desc);
                if (json.has("limitDepts")) {
                    limitDepts = json.getString("limitDepts");
                }
            } catch (JSONException e) {
                LogUtil.getLog(getClass()).error(e);
            }
        }

        String str = "";
        String deptNames = "";
        String v = StrUtil.getNullStr(ff.getValue());
        if (!"".equals(v)) {
            DeptDb dd = new DeptDb();

            String[] fields = v.split(",");
            for (String deptCode : fields) {
                dd = dd.getDeptDb(deptCode);
                String deptName = dd.getName();
                if ("".equals(deptNames)) {
                    deptNames = deptName;
                } else {
                    deptNames += "," + deptName;
                }
            }
        }
        str += "<div class='user_group_box'>";
        str += "<textarea id='" + ff.getName() + "_realshow' name='" + ff.getName() + "_realshow" +
                "' readonly style='float:left; width:" + ff.getCssWidth() + "' rows='3'>" + deptNames + "</textarea>";
        str += "<input id='" + ff.getName() + "' name='" + ff.getName() + "' value='" + v + "' type='hidden' />";
        str += "<div id='" + ff.getName() + "_btn' class='user_group_btn' onclick='openWinDeptsSelect(fo(\"" + ff.getName() + "\"), false, \"" + limitDepts + "\")'></div>";
        str += "</div>";

        str += "<script>";
        str += "$('#" + ff.getName() + "_btn').hover(\n";
        // str += "function() {$('#" + ff.getName() + "_btn').toggleClass('user_group_btn_hover');},\n";
        str += "function() {$(fo('" + ff.getName() + "_btn')).toggleClass('user_group_btn_hover');}\n";
        str += ");\n";
        str += "</script>";

        return str;
    }

    @Override
    public String getControlType() {
        return "select";
    }

    /**
     * 手机端
     *
     * @param userName
     * @param ff
     * @return
     * @Description:
     */
    @Override
    public String getControlOptions(String userName, FormField ff) {
        String res = "";
        UserDb ud = new UserDb();
        ud = ud.getUserDb(userName);
        String unitcode = ud.getUnitCode();
        // 可能是用admin账户进行测试
        if (StrUtil.isEmpty(unitcode)) {
            unitcode = DeptDb.ROOTCODE;
        }
        String deptCode = unitcode;

        String desc = ff.getDescription();
        if (StringUtils.isNotEmpty(desc)) {
            org.json.JSONObject json;
            try {
                json = new org.json.JSONObject(desc);
                if (json.has("limitDepts")) {
                    deptCode = json.getString("limitDepts");
                }
            } catch (JSONException e) {
                LogUtil.getLog(getClass()).error(e);
            }
        }

        JSONArray childrens = new JSONArray();
        try {
            DeptSelectCtl deptSelectCtl = new DeptSelectCtl();
            res = deptSelectCtl.getDeptNameAsOptions(deptCode, childrens, true).toString();

            JSONArray ary = new JSONArray();
            JSONObject children = new JSONObject();
            children.put("name", ConstUtil.NONE);
            children.put("value", "");
            ary.add(children);

            JSONArray jsonAry = JSONArray.parseArray(res);
            for (int i = 0; i < jsonAry.size(); i++) {
                ary.add(jsonAry.get(i));
            }
            res = ary.toString();
        } catch (ErrMsgException e) {
            LogUtil.getLog(getClass()).error(e);
        }
        return res;
    }

    @Override
    public String getControlValue(String s, FormField formField) {
        return StrUtil.getNullStr(formField.getValue());
    }

    @Override
    public String getControlText(String s, FormField ff) {
        return "";
    }

    /**
     * 显示在列表中的值，此处参照单部门选择框，只是显示样式不同，需要对数据
     * 做处理,与多用户选择框相似
     *
     * @param request    HttpServletRequest
     * @param ff         FormField
     * @param fieldValue String 格式：a,b
     * @return
     */
    @Override
    public String converToHtml(HttpServletRequest request, FormField ff, String fieldValue) {
        String v = StrUtil.getNullStr(fieldValue);
        if (!"".equals(v)) {
            DeptDb dd = new DeptDb();
            StringBuffer deptNames = new StringBuffer();
            String[] fields = v.split(",");
            for (String deptCode : fields) {
                dd = dd.getDeptDb(deptCode);
                String deptName = dd.getName();

                StrUtil.concat(deptNames, ",", deptName);
            }
            return deptNames.toString();
        } else {
            return "";
        }
    }


    /**
     * 当report时，取得用来替换控件的脚本
     *
     * @param ff FormField
     * @return String
     */
    @Override
    public String getReplaceCtlWithValueScript(FormField ff) {
        String v = "";
        if (ff.getValue() != null && !"".equals(ff.getValue())) {
            DeptDb dd = new DeptDb();
            String[] ary = StrUtil.split(ff.getValue(), ",");
            for (String s : ary) {
                dd = dd.getDeptDb(s);
                if ("".equals(v)) {
                    v = dd.getName();
                } else {
                    v += "," + dd.getName();
                }
            }
        }
        String str = "$('#" + ff.getName() + "_btn').hide();\n";
        return str + "ReplaceCtlWithValue('" + ff.getName() + "_realshow', '" + ff.getType() + "','" + v + "');\n";
    }

    @Override
    public String getDisableCtlScript(FormField ff, String formElementId) {
        String realName = "";
        if (ff.getValue() != null && !"".equals(ff.getValue())) {
            String[] ary = StrUtil.split(ff.getValue(), ",");
            DeptDb dd = new DeptDb();
            for (String s : ary) {
                dd = dd.getDeptDb(s);
                if ("".equals(realName)) {
                    realName = dd.getName();
                } else {
                    realName += "," + dd.getName();
                }
            }
        }

        String str = "DisableCtl('" + ff.getName() + "', '" + ff.getType() +
                "','" + realName + "','" + ff.getValue() + "');\n";
        str += "DisableCtl('" + ff.getName() + "_realshow', '" + ff.getType() +
                "','" + "" + "','" + ff.getValue() + "');\n";
        str += "if (fo('" + ff.getName() + "_btn')) fo('" + ff.getName() + "_btn').outerHTML='';";
        return str;
    }


    @Override
    public String getValueByName(FormField formField, String name) {
        /*String[] newDeptName = StrUtil.split(name, "\\\\");
        if (newDeptName==null) {
            LogUtil.getLog(getClass()).error("部门:" + name + " 为空！");
            return "";
        }*/

        name = name.replaceAll("，", ",");

        StringBuilder sb = new StringBuilder(10);
        String[] ary = name.split(",");
        if (ary.length > 0) {
            IDepartmentService departmentService = SpringUtil.getBean(IDepartmentService.class);
            Map<String, String> map = departmentService.getFulleNameMap();
            for (String nm : ary) {
                Department department = departmentService.getDepartmentByName(nm);
                if (department != null) {
                    StrUtil.concat(sb, ",", department.getCode());
                } else {
                    // 如果未找到，则可能导入时可能用的是全路径名：行政部\秘书科\秘书一组
                    String deptCode = map.get(nm);
                    if (deptCode == null || "".equals(deptCode)) {
                        LogUtil.getLog(getClass()).error("部门：" + nm + " 不存在！");
                        return "";
                    } else {
                        StrUtil.concat(sb, ",", deptCode);
                    }
                }
            }
        }
        return sb.toString();
    }

    @Override
    public Object getValueForSave(FormField ff, int flowId, FormDb fd, FileUpload fu) {
        if (fu.getFieldValues(ff.getName()) != null) {
            return String.join(",", fu.getFieldValues(ff.getName()));
        } else {
            return StrUtil.emptyTo(fu.getFieldValue(ff.getName()), "");
        }
    }
}
